<template>
  <modal-draggable
    :show="showModal"
    preset="dialog"
    :show-icon="false"
    :title="Object.keys(editorData).length > 0 ? '编辑' : '新增'"
    :positive-text="'确定'"
    :negative-text="'取消'"
    :style="{
      width: '640px'
    }"
    @positive-click="submitCallback"
    @negative-click="cancelCallback"
    @close="cancelCallback"
  >
    <div class="form-content">
      <n-form
        ref="formRef"
        :model="editorDataList"
        :rules="rules"
        label-placement="left"
        label-width="auto"
        require-mark-placement="right-hanging"
        size="medium"
        :style="{
          maxWidth: '640px'
        }"
      >
        <n-form-item label="采购订单ID" path="orderId"><n-input
            v-model:value="editorDataList.orderId"
            placeholder="请输入采购订单ID"
            clearable
            :maxlength="20"
            show-count
          />
        </n-form-item>
        <n-form-item label="订单详情ID" path="detailId"><n-input
            v-model:value="editorDataList.detailId"
            placeholder="请输入订单详情ID"
            clearable
            :maxlength="20"
            show-count
          />
        </n-form-item>
        <n-form-item label="订单创建日期" path="orderDate"><n-input
            v-model:value="editorDataList.orderDate"
            placeholder="请输入订单创建日期"
            clearable
            :maxlength="20"
            show-count
          />
        </n-form-item>
        <n-form-item label="产品名称" path="productName"><n-input
            v-model:value="editorDataList.productName"
            placeholder="请输入产品名称"
            clearable
            :maxlength="20"
            show-count
          />
        </n-form-item>
        <n-form-item label="产品购买数量" path="quantity"><n-input
            v-model:value="editorDataList.quantity"
            placeholder="请输入产品购买数量"
            clearable
            :maxlength="20"
            show-count
          />
        </n-form-item>
        <n-form-item label="产品单价" path="unitPrice"><n-input
            v-model:value="editorDataList.unitPrice"
            placeholder="请输入产品单价"
            clearable
            :maxlength="20"
            show-count
          />
        </n-form-item>
        <n-form-item label="合计金额" path="totalAmount"><n-input
            v-model:value="editorDataList.totalAmount"
            placeholder="请输入合计金额"
            clearable
            :maxlength="20"
            show-count
          />
        </n-form-item>
        <n-form-item label="订单状态" path="orderStatus">
            <n-select
            v-model:value="editorDataList.orderStatus"
            placeholder="请选择订单状态"
            :options="orderStatusOptions"
            @update-value="orderStatusChange"
            clearable
          />
        </n-form-item>
      </n-form>
    </div>
  </modal-draggable>
</template>

<script lang="ts">
  import { defineComponent, ref, watchEffect, PropType } from 'vue'
  import { FormInst, useMessage } from 'naive-ui'
  import type { FormItemRule } from 'naive-ui'
  import { Row } from './home'
  import ModalDraggable from 'udp/components/tools/modal-draggable.vue'
  import { addItem, updateItem } from './api'
  export default defineComponent({
    components: { ModalDraggable },
    props: {
      showModal: {
        type: Boolean,
        default: false
      },
      editorData: {
        type: Object as PropType<Row>,
        default: () => {
          return {}
        }
      }
    },
    emits: ['refresh', 'update:showModal'],
    setup(props, { emit }) {
      // 初始化数据
      const editorDataList = ref<Row>({ id: '', orderId:'', detailId:'', orderDate:'', productName:'', quantity:'', unitPrice:'', totalAmount:'', orderStatus:''})
      const formRef = ref<FormInst | null>(null)
      const message = useMessage()
      
      const orderStatusOptions = [
        {
          label:'创建订单',
          value:'0'
        },
        {
          label:'订单发货',
          value:'1'
        },
        {
          label:'订单完成',
          value:'2'
        },
        ]  
        
      
      // 监听props变化
      watchEffect(() => {
        if (props.showModal) {
          nextTick(() => {
            let obj ={ ...props.editorData }
            for(const key in obj){
              obj[key] += ''
            }
            editorDataList.value = { ...obj }
          })
        }

      })

      // 关闭弹框
      const cancelCallback = () => emit('update:showModal', false)

      // 表单提交
      const submitCallback = () => {
        formRef.value?.validate(errors => {
          if (!errors) {
            // console.log(editorDataList, 'editorDataList')
            const isAdd = !(Object.keys(props.editorData).length > 0)
            if (isAdd) {
              // console.log('新建')
              delete editorDataList.value.id
              addItem(editorDataList.value).then((res: any) => {
                if (res.code == 0) {
                  message.success(res.message)
                  emit('refresh')
                  cancelCallback()
                } else {
                  message.error('失败')
                }
              })
            } else {
              updateItem(editorDataList.value).then((res: any) => {
                if (res.code == 0) {
                  message.success(res.message)
                  emit('refresh')
                  cancelCallback()
                } else {
                  message.error('失败')
                }
              })
            }
          }
        })
      }
      return {
        formRef,
        editorDataList,
        rules: {
          orderId: {
            required: true,
            trigger: 'blur',
            validator(rule: FormItemRule, value: string) {
              if (!value) {
                return new Error('必填项 采购订单ID 不能为空')
              } 
              return true
            }
          },
          detailId: {
            required: true,
            trigger: 'blur',
            validator(rule: FormItemRule, value: string) {
              if (!value) {
                return new Error('必填项 订单详情ID 不能为空')
              } 
              return true
            }
          },
          orderDate: {
            required: true,
            trigger: 'blur',
            validator(rule: FormItemRule, value: string) {
              if (!value) {
                return new Error('必填项 订单创建日期 不能为空')
              } 
              return true
            }
          },
          productName: {
            required: true,
            trigger: 'blur',
            validator(rule: FormItemRule, value: string) {
              if (!value) {
                return new Error('必填项 产品名称 不能为空')
              } 
              return true
            }
          },
          quantity: {
            required: true,
            trigger: 'blur',
            validator(rule: FormItemRule, value: string) {
              if (!value) {
                return new Error('必填项 产品购买数量 不能为空')
              } 
              return true
            }
          },
          unitPrice: {
            required: true,
            trigger: 'blur',
            validator(rule: FormItemRule, value: string) {
              if (!value) {
                return new Error('必填项 产品单价 不能为空')
              } 
              return true
            }
          },
          totalAmount: {
            required: true,
            trigger: 'blur',
            validator(rule: FormItemRule, value: string) {
              if (!value) {
                return new Error('必填项 合计金额 不能为空')
              } 
              return true
            }
          },
          orderStatus: {
            required: true,
            trigger: 'blur',
            validator(rule: FormItemRule, value: string) {
              if (!value) {
                return new Error('必填项 订单状态 不能为空')
              } 
              return true
            }
          }
        },
        submitCallback,
        cancelCallback,
        orderStatusChange: value => {
          console.log(value)
        },
        orderStatusOptions
      }
    }
  })
</script>
<style lang="less" scoped>
  .form-content {
    padding: 20px;
    background-color: #fff;
  }
</style>
